package com.ruoyi.hospital.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

public class phpSecret {
    public static String phpSign(String key, Map<String, Object> map) {
        //key = "cspAVFPPuv2eWpShAekNnaCJXXrU5R28";
        try {
            map.remove("sign");

            // 使用 TreeMap 来对键进行排序
            TreeMap<String, Object> sortedMap = new TreeMap<>(map);

            StringBuilder beforeSignStrBuilder = new StringBuilder();
            for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
                beforeSignStrBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            String beforeSignStr = beforeSignStrBuilder.toString();
            beforeSignStr = beforeSignStr.substring(0, beforeSignStr.length() - 1) + key;


            String sign = md5(beforeSignStr);
            System.out.println("签名参数: " + beforeSignStr);
            System.out.println("签名: " + md5(beforeSignStr));
            return sign;

        } catch (Exception e) {
            System.out.println("err");
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static String md5(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(s.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
